package com.bnz.servlet;

import cn.hutool.core.util.StrUtil;
import com.bnz.pojo.Cart;
import com.bnz.pojo.Product;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/cart")
public class CartServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1. 得到请求参数
		String cmd = req.getParameter("cmd");
		//2. 根据参数调用方法
		if(StrUtil.isNotBlank(cmd)){
			if("add".equals(cmd)){      // 添加购物车
				add(req,resp);
			}
		}
	}
	//1. 添加购物车
	private void add(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
		//1.1 得到要添加的商品id
		String pid = req.getParameter("pid");
		//1.2 得到ServletContext中所有的商品列表
		ServletContext servletContext = req.getServletContext();
		Map<String, Product> products = (Map<String, Product>) servletContext.getAttribute("products");
		//1.3 根据key得到值
		Product product = products.get(pid);
		//1.4 得到购物车对象
		//1.4.1 得到HttpSession对象
		HttpSession session = req.getSession();
		//1.4.2 从session中得到购物车
		Cart cart = (Cart) session.getAttribute("cart");
		//1.4.3 如果第一次购物商品，没有购物车就构造一个购物车
		if(cart == null){
			cart = new Cart();
		}
		//1.4.4 添加商品到购物车中
		cart.add(product);
		//1.4.5 将购物车放到session中
		session.setAttribute("cart",cart);

		//1.4.6 跳转到购物车列表页面
		resp.sendRedirect("/cart_list.jsp");

	}
}

